package top.shiyiri.collection;

import org.junit.Test;

import java.util.*;

/**
 * @author Aunean
 * @date 2022/1/15 21:52
 */
public class CollectionTest {

    //Java8中的写法
    @Test
    public void test1() {
        List<String> list = new ArrayList<>();
        list.add("Joe");
        list.add("Bob");
        list.add("Bill");
        //返回的 list 是一个只读的集合
        list = Collections.unmodifiableList(list);
        list.add("23");
        System.out.println(list);
    }

    @Test
    public void test2() {
        List<String> list = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
        Set<String> set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a",
                "b", "c")));
        //如下操作不适用于jdk 8 及之前版本,适用于jdk 9
        Map<String, Integer> map = Collections.unmodifiableMap(new HashMap<>() {
            {
                put("a", 1);
                put("b", 2);
                put("c", 3);
            }
        });
        map.forEach((k, v) -> System.out.println(k + ":" + v));
    }

    @Test
    public void test3() {
        //此时得到的 list 也是一个只读集合
        List<Integer> list = Arrays.asList(12, 2, 3, 4);
        list.add(3);//java.lang.UnsupportedOperationException
    }

    //Java9新特性：集合工厂方法：创建只读集合
    @Test
    public void test4() {
        List<Integer> list = List.of(12, 2, 3, 4);
        //list.add(3);UnsupportedOperationException

        Set<Integer> integers = Set.of(2, 323, 123, 23, 5);
        //integers.add(3);//UnsupportedOperationException
        System.out.println(integers);

        Map<String, Integer> map = Map.of("Tom", 12, "Jerry", 23, "Anna", 21);
        //map.put("Line", 23);//UnsupportedOperationException

        Map<String, Integer> entries = Map.ofEntries(Map.entry("Tom", 12), Map.entry("Jerry", 23));
        //entries.put("23", 2);//UnsupportedOperationException
        System.out.println(entries);
    }
}
